package gk.example.activity;

import gk.example.App;
import gk.example.BaseActivity;
import gk.example.adapter.ChatAdapter;
import gk.example.bean.MsgRecord;
import gk.example.bean.User;
import gk.example.util.ErrorCodeUtil;
import gk.example.view.ProgressDialog;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.BmobPushManager;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.example.gkdate.R;

public class ChatActivity extends BaseActivity implements OnClickListener {
	private ListView mLvChat;
	private ChatAdapter mChatAdapter;
	private ImageButton mBtnBack;
	private TextView mTvTitle;
	private Button mBtnSend;
	private EditText mEtContent;
	private ArrayList<String> mName;
	private ArrayList<String> mMsg;
	private ArrayList<String> mId;
	MsgReceiver msgReceiver;
	IntentFilter intentFilter;
	private ProgressDialog progressDialog;

	@Override
	protected void initView() {
		setContentView(R.layout.activity_chat);
		mLvChat = (ListView) findViewById(R.id.lv_chat);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mTvTitle = (TextView) findViewById(R.id.tv_top_title);
		mBtnSend = (Button) findViewById(R.id.btn_send_message);
		mEtContent = (EditText) findViewById(R.id.et_chat_content);
		mName = new ArrayList<String>();
		mMsg = new ArrayList<String>();
		mId = new ArrayList<String>();
		mChatAdapter = new ChatAdapter(this, mName, mMsg, mId);
		msgReceiver = new MsgReceiver();
		intentFilter = new IntentFilter();
		progressDialog = new ProgressDialog();
	}

	@Override
	protected void initEvent() {
		intentFilter.addAction("android.intent.action.MsgReceiver");
		registerReceiver(msgReceiver, intentFilter);
		mTvTitle.setText("聊一聊");
		mBtnBack.setOnClickListener(this);
		mBtnSend.setOnClickListener(this);
		mLvChat.setAdapter(mChatAdapter);
		Intent intent = getIntent();
		String dataid = null;
		if (intent.getStringExtra("DataId") != null) {
			dataid = intent.getStringExtra("DataId");
		} else {
			dataid = App.DateInfo.getObjectId();
		}
		getMessage(dataid);
	}

	/**
	 * 
	 * 描述： 获取初始消息
	 * 
	 * @return void
	 */
	private void getMessage(String dataid) {

		progressDialog.show(getSupportFragmentManager(), "");
		BmobQuery<MsgRecord> query = new BmobQuery<MsgRecord>();
		query.addWhereMatches("dateInfo", dataid);
		query.findObjects(this, new FindListener<MsgRecord>() {

			@Override
			public void onSuccess(List<MsgRecord> arg0) {
				if (arg0.size() > 0) {
					getUserData(arg0);
				} else {
					progressDialog.dismiss();
				}

			}

			@Override
			public void onError(int arg0, String arg1) {
				progressDialog.dismiss();
				ErrorCodeUtil.Errorshow(ChatActivity.this, arg0, "拉取消息失败");
			}
		});
	}

	private int markForUser = 0;

	/**
	 * 
	 * 描述：获取用户信息
	 * 
	 * @param dateList
	 * @return void
	 */
	private void getUserData(final List<MsgRecord> msgRecord) {
		BmobQuery<User> query = new BmobQuery<User>();
		query.addWhereMatches("objectId", msgRecord.get(markForUser)
				.getSender().getObjectId());
		query.findObjects(this, new FindListener<User>() {
			@Override
			public void onSuccess(List<User> arg0) {
				markForUser++;
				mName.add(arg0.get(0).getNickName());
				if (markForUser != msgRecord.size()) {
					getUserData(msgRecord);
					return;
				}
				markForUser = 0;
				for (int i = 0; i < msgRecord.size(); i++) {
					mMsg.add(msgRecord.get(i).getMessage());
					mId.add(msgRecord.get(i).getSender().getObjectId());
					mChatAdapter.notifyDataSetChanged();
				}
				progressDialog.dismiss();
			}

			@Override
			public void onError(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(ChatActivity.this, arg0, "加载失败");
				progressDialog.dismiss();
			}

		});
	}

	/**
	 * 
	 * 描述： 发送消息
	 * 
	 * @return void
	 */
	private void sendMessage() {
		final String content = mEtContent.getText().toString();
		if (mEtContent.equals("")) {
			return;
		}
		final MsgRecord msgRecord = new MsgRecord();
		msgRecord.setMessage(content);
		msgRecord.setSender(App.BmobUser);
		msgRecord.setDateInfo(App.DateInfo);
		msgRecord.save(this, new SaveListener() {

			@Override
			public void onSuccess() {
				addRecord(content, msgRecord);
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(ChatActivity.this, arg0, "发送失败");
			}
		});

	}

	/**
	 * 
	 * 描述：添加聊天记录到约会
	 * 
	 * @param content
	 * @return void
	 */
	private void addRecord(final String content, final MsgRecord msgRecord) {
		BmobRelation bmobRelation = new BmobRelation();
		bmobRelation.add(msgRecord);
		App.DateInfo.setMsgRecord(bmobRelation);
		App.DateInfo.update(this, new UpdateListener() {

			@Override
			public void onSuccess() {
				pushMessage(msgRecord);
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				ErrorCodeUtil.Errorshow(ChatActivity.this, arg0, "发送失败");
			}
		});
	}

	/**
	 * 
	 * 描述：推送消息
	 * 
	 * @param content
	 * @return void
	 */
	private void pushMessage(final MsgRecord msgRecord) {
		mEtContent.setText("");
		mId.add(App.BmobUser.getObjectId());
		mMsg.add(msgRecord.getMessage());
		mName.add(App.BmobUser.getUsername());
		mChatAdapter.notifyDataSetChanged();
		for (int i = 0; i < App.Attender.size(); i++) {
			if (App.Attender.get(i).getObjectId()
					.equals(App.BmobUser.getObjectId())) {

			} else {
				String installationId = App.Attender.get(i).getIntall();
				BmobPushManager<BmobInstallation> bmobPush = new BmobPushManager<BmobInstallation>(
						ChatActivity.this);
				BmobQuery<BmobInstallation> query = BmobInstallation.getQuery();
				query.addWhereEqualTo("installationId", installationId);
				bmobPush.setQuery(query);
				JSONObject jObject = new JSONObject();
				try {
					jObject.put("Msg", msgRecord.getMessage());
					jObject.put("Activity", "ChatActivity");
					jObject.put("SenderName", App.BmobUser.getNickName());
					jObject.put("DateId", App.DateInfo.getObjectId());
					bmobPush.pushMessage(jObject);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(msgReceiver);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_send_message:
			sendMessage();
			break;
		default:
			break;
		}
	}

	public class MsgReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			mMsg.add(intent.getExtras().getString("Msg"));
			mName.add(intent.getExtras().getString("SenderName"));
			mId.add(intent.getExtras().getString("DateId"));
			mChatAdapter.notifyDataSetChanged();
		}
	}

}
